# 信息处理 读数据 拼接字符串数据 写入文件

ABSOLUTE_PATH = r'D:\Files\Python\ATM\user_info\\'


def read_data(tag, path):
    try:
        with open(f"{ABSOLUTE_PATH}{path}", 'r', encoding='utf8') as fp:
            data = fp.read().split('\n')
            data_dict = {}
            for i in data:
                if i == '':
                    continue
                if tag == 'info':
                    username, bank_id, pay_pwd, balance = i.split('|')
                    data_dict[username] = {'id': bank_id, 'pay_pwd': pay_pwd, 'balance': int(balance)}
                elif tag == 'pwd':
                    username, password = i.split('|')
                    data_dict[username] = {'pwd': password}
            return data_dict
    except Exception as e:
        return f"文件读取失败，错误信息是{e}"


# 将数据转成字符串
def save_data(*args, **kwargs):
    save_dict = '|'.join([str(value) for value in kwargs.values()])
    if args[0] == 'info':
        flag, msg = save_file(path='all_info.txt', data=save_dict)
        return flag, msg
    elif args[0] == 'pwd':
        flag, msg = save_file(path='all_pwd.txt', data=save_dict)
        return flag, msg


# 将字符串写入文件中
def save_file(path, data):
    try:
        with open(f"{ABSOLUTE_PATH}{path}", 'a') as fp:
            fp.write(data + '\n')
            fp.flush()
            return True, "文件写入成功！"
    except Exception as e:
        return False, f"文件写入失败，错误信息：{e}"


# 将字符串写入流水中
def save_flow(state, user, txt):
    try:
        if state == 'save':
            with open(f'{ABSOLUTE_PATH}{user}_flow.txt', 'a', encoding='utf8') as fp:
                fp.write(txt + '\n')
        elif state == 'read':
            with open(f'{ABSOLUTE_PATH}{user}_flow.txt', 'r', encoding='utf8') as fp:
                return fp.read()
    except Exception as e:
        return f"文件写入/读取失败，错误信息为{e}"
